package com.linkstec.base.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.linkstec.base.constant.SysConstant;
import com.linkstec.base.menus.TicketTypeEnum;
import com.linkstec.base.service.WechatConfigService;
import com.linkstec.base.service.WechatExternalContactService;
import com.linkstec.base.util.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.Map;

@RestController
@RequestMapping("/linkstec-wechat")
public class WechatController {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    PropUtil propUtil;
    @Autowired
    private WechatConfigService wechatConfigService;


    Logger logger = LoggerFactory.getLogger(WechatController.class);

    /**
     * 获得授权事件的票据.
     *
     * @param timestamp    时间戳
     * @param nonce        随机数
     * @param encryptType  加密类型 aes
     * @param msgSignature 消息体签名
     * @param postdata     消息体
     * @return 如果获得只需要返回 SUCCESS
     */
    @RequestMapping("/ticket")
    public String ticket(String timestamp, String nonce,
                         @RequestParam("encrypt_type") String encryptType,
                         @RequestParam("msg_signature") String msgSignature,
                         @RequestBody String postdata) {
        try {
            //这个类是微信官网提供的解密类,需要用到消息校验Token 消息加密Key和服务平台appid
            WXBizMsgCrypt pc = new WXBizMsgCrypt(propUtil.COMPONENT_TOKEN,
                    propUtil.aesKey, propUtil.wechat_app_id);
            String xml = pc.decryptMsg(msgSignature, timestamp, nonce, postdata);
            Map<String, String> result = Xml2MapUtil.xmlToMap(xml);// 将xml转为map
            String componentVerifyTicket = result.get("ComponentVerifyTicket");
            // 存储平台授权票据,保存ticket 12小时
            redisUtil.set(SysConstant.ComponentVerifyTicket, componentVerifyTicket, 43200l);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return "success";
    }


    /**
     * 获取config参数
     *
     * @param jsonObject
     * @return
     */
    @PostMapping(value = "/get/config")
    public DataResultUtil getConfigParameter(@RequestBody JSONObject jsonObject) {
        String url = jsonObject.getString("url");
        try {
            if (StringUtils.isEmpty(url)) {
                return DataResultUtil.getFailureResult("url不能为空", null);
            }
            url = URLDecoder.decode(url, "utf-8");
            return wechatConfigService.getConfig(url);
        } catch (Exception e) {
            e.printStackTrace();
            return DataResultUtil.getFailureResult("查询异常", null);
        }
    }


}
